import pymongo


# 初始化
def initDatabase(DatabaseName: str):
    """
    :param DatabaseName: 数据库名称
    :return: 数据库对象
    """
    # 连接mongo数据库，使用的是本地的mongo
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    # 创建对应数据库名称的实例对象，里面传的string是数据库名称
    db = client[DatabaseName]
    return db


# 查询
def find_data(DataBaseObject, find_condition, find_choice, colletionName: str, projection={"output": 0}):
    """
    :param projection:
    :param DataBaseObject:
    :param find_condition:
    :param find_choice:
    :param colletionName:
    :return:
    """
    ans = None
    if find_choice == "one":
        ans = DataBaseObject[colletionName].find_one(find_condition)
    elif find_choice == "many":
        save = DataBaseObject[colletionName].find(find_condition)
        ans = []
        for item in save:
            ans.append(item)
    return ans


# 删除数据
def deleteData(DataBaseObject, delete_condition, del_choice, colletionName: str):
    """
    :param DataBaseObject:
    :param delete_condition: 删除的条件
    :param del_choice: 是需要针对条件完全删除还是仅删除一条
    :param colletionName:
    :return:
    """
    ans = None
    if del_choice == "one":
        # 根据查询条件进行删除,只删除一条符合要求的数据
        ans = DataBaseObject[colletionName].find_one_and_delete(delete_condition)
    elif del_choice == "many":
        ans = DataBaseObject[colletionName].delete_many(delete_condition)
    # print("ans_count", ans)
    if ans != None:
        print("成功")
        return {"res": "del_success"}
    else:
        print("失败")
        return {"res": "del_fail"}


# 修改数据
def update_data(DataBaseObject, updateFind_condition, updateMain_condition, update_choice, colletionName: str):
    """
    :param DataBaseObject: 数据库对象
    :param updateFind_condition: 查找对应条件的记录以进行更新
    :param updateMain_condition: 更新条件
    :param update_choice: 确定是多条更新还是单条更新
    :param colletionName: 集合名称
    :return:
    """
    ans = None
    update_setString = {'$set': updateMain_condition}
    if update_choice == "one":
        # 根据查询条件进行删除,只删除一条符合要求的数据
        ans = DataBaseObject[colletionName].find_one_and_update(updateFind_condition, update_setString)
    elif update_choice == "many":
        ans = DataBaseObject[colletionName].update_many(updateFind_condition, update_setString)
    # print("ans_count", ans.updated_count)
    if ans:
        print("成功")
        return {"res": "update_success"}
    else:
        print("失败")
        return {"res": "update_fail"}


# 添加数据
def addData(DataBaseObject, addData, colletionName: str):
    """
        :param DataBaseName: 数据库对象
        :param colletionName: 集合名称
        :param addData: 添加的数据
        :return:提示信息
    """
    # 判断添加类型，如果是对象数组形式那么就是 添加多条数据的函数实现
    if isinstance(addData, list):
        a = DataBaseObject[colletionName].insert_many(addData)
        if a:
            return {"res": "success", "data": "addList"}
    elif isinstance(addData, dict):
        b = DataBaseObject[colletionName].insert_one(addData)
        if b:
            return {"res": "success", "data": "addDict","id_": str(b.inserted_id)}
    else:
        return {"res": "fail", "data": "error"}


# print(mydb_collist)
# collections = db.test_1  # 创建集合,student 相当于 mysql 的表名
# print(collections)
# result2 = collections.find()
# print(result2)
#

# info = {
#     'name': 'www',
#
# }
# newone = {
#     'age': 23
# }
# findjson = {
#     "edfqwed": "safqwdqwd"
# }
# addData(db,  book_info, "aaa" )
# deleteData(db, info, "many", "test_1")
# update_data(db, info, newone, "one", "test_1")
# result = collections.insert_one(book_info)
# result = find_data(db, findjson, "many", "test_1")
# print(result)
# print(result.inserted_id)
#
# # result = collections.find_one({})
# result = collections.find({})
#
# print(type(result))
# for r in result:
#     print(r)

#
# find_json = {
#
# }
# db = initDatabase("userDatabase")
# ans = find_data(db, find_json, 'many', 'model')
#
#
# def split_array(array, chunk_size):
#     """
#     将数组拆分成指定大小的子数组
#     """
#     assert chunk_size > 0, "chunk_size必须大于0."
#     return [array[i:i + chunk_size] for i in range(0, len(array), chunk_size)]
#
#
# oo = split_array(ans, 3)
# print("ans", ans, len(ans), len(oo))
